package com.weilai.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.weilai.controller.exceptionHandler.BusinessException;
import com.weilai.controller.exceptionHandler.Code;
import com.weilai.domain.*;
import com.weilai.service.AdminService;
import com.weilai.service.RepliesService;
import com.weilai.service.ReportInfoService;
import com.weilai.service.UserService;
import com.weilai.service.serviceImpl.CommentsServiceImpl;
import com.weilai.service.serviceImpl.PostsServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping("/admin")
@Api(tags = "管理员", description = "执行管理员的所有操作")
public class AdminController {
    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Autowired
    private AdminService adminService;
    @Autowired
    private UserService userService;
    @Autowired
    private ReportInfoService reportInfoService;
    @Autowired
    private PostsServiceImpl postsServiceImpl;


    // 3.3 分类管理
    @ApiOperation("查询分类列表")
    @GetMapping("/behindManagerCategory")
    public ModelAndView selectAllCategories(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                            @RequestParam(value = "pageSize", defaultValue = "4") int pageSize,
                                            HttpServletRequest request) throws BusinessException {
        PageInfo<Categories> pageInfo = adminService.getCategoriesFromManagerWithPaging(pageNum, pageSize);
        User admin = (User) request.getSession().getAttribute("user");
        ModelAndView mav = new ModelAndView("behindManagerCategory");
        mav.addObject("categoryList", pageInfo.getList());
        mav.addObject("totalPages", pageInfo.getPages());
        mav.addObject("admin", admin);
        return mav;
    }

    @ApiOperation("类别分页")
    @ResponseBody
    @GetMapping("/getCategoriesFromManagerWithPaging")
    public Map<String, Object> getCategoriesFromManagerWithPaging(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                                                  @RequestParam(value = "pageSize", defaultValue = "4") int pageSize,
                                                                  HttpServletRequest request) {

        PageInfo<Categories> pageInfo = adminService.getCategoriesFromManagerWithPaging(pageNum, pageSize);
        List<Categories> list = pageInfo.getList();
        Map<String, Object> response = new HashMap<>();
        if (list.isEmpty()) {
            response.put("info", "暂无帖子");
        }
        response.put("list", list);
        response.put("totalPage", pageInfo.getPages());

        User admin = (User) request.getSession().getAttribute("user");
        response.put("admin",admin);
        return response;
    }

    @ApiOperation("按ID修改分类")
    @PostMapping("/toUpdateCategory")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> updateCategory(@RequestParam("id") int categoryId, String name, String description) {
        // 此方法返回 ResponseEntity，无需 ModelAndView，故不处理
        Map<String, Object> result = new HashMap<>();
        try {
            Categories category = adminService.selectCategoryById(categoryId);
            if (category != null) {
                category.setName(name);
                category.setDescription(description);
                adminService.manageCategory(category);
                List<Categories> categoryList = adminService.selectAllCategory();
                result.put("categoryList", categoryList);
                result.put("success", true);
                result.put("message", "修改成功");
                result.put("redirectUrl", "/admin/behind-manager-category");


                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "未找到该类别");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
        } catch (BusinessException e) {
            result.put("success", false);
            result.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    @ApiOperation("添加分类")
    @PostMapping("/toInsertCategory")
    public String insertCategory(
            @RequestParam("name") String name,
            @RequestParam("description") String description,
            HttpServletRequest request,
            RedirectAttributes redirectAttributes) throws BusinessException {
        // 重定向方法，无需 ModelAndView，故不处理
        User admin = (User) request.getSession().getAttribute("user");
        if (admin == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录");
            return "redirect:/login";
        }
        Categories newCategory = new Categories();
        newCategory.setName(name);
        newCategory.setDescription(description);
        newCategory.setCreatedBy(admin.getId());
        adminService.insertCategory(newCategory);
        redirectAttributes.addFlashAttribute("info", "添加成功");
        return "redirect:/admin/behindManagerCategory";
    }

    @ApiOperation("按ID删除分类")
    @GetMapping("/toDeleteCategory")
    public String deleteCategory(@RequestParam("id") int id, RedirectAttributes redirectAttributes)
            throws BusinessException {
        // 重定向方法，无需 ModelAndView，故不处理
        adminService.deleteCategoryById(id);
        redirectAttributes.addFlashAttribute("info", "删除成功");
        return "redirect:/admin/behindManagerCategory";
    }

    // 3.4 帖子审核
    @ApiOperation("查询待审核帖子")
    @GetMapping("/behindManagerPost")
    public ModelAndView allPostsUnderChecking(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                              @RequestParam(value = "pageSize", defaultValue = "4") int pageSize,
                                              HttpServletRequest request) throws BusinessException { // 添加 request 参数
        PageInfo<Posts> pageInfo = adminService.getPostsFromManagerWithPaging(pageNum, pageSize);
        List<Posts> posts = pageInfo.getList();
        String info = "";
        List<String> usernames = new ArrayList<>();
        if (posts == null) {
            info = "没有未审核的帖子";
        }
        if (posts != null) {
            for (Posts posts1 : posts) {
                User user = userService.getUserById(posts1.getUserId());
                usernames.add(user.getUsername());
            }
        }
        ModelAndView mav = new ModelAndView("behindManagerPost");
        mav.addObject("postsList", posts);
        mav.addObject("usernameList", usernames);
        mav.addObject("totalPages", pageInfo.getPages());
        mav.addObject("info", info);


        User admin = (User) request.getSession().getAttribute("user");
        mav.addObject("admin", admin);

        return mav;
    }

    @ApiOperation("帖子分页")
    @ResponseBody
    @GetMapping("/getPostsFromManagerWithPaging")
    public Map<String, Object> getPostsFromManagerWithPaging(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                                             @RequestParam(value = "pageSize", defaultValue = "4") int pageSize,
                                                             HttpServletRequest request) {

        PageInfo<Posts> pageInfo = adminService.getPostsFromManagerWithPaging(pageNum, pageSize);
        List<Posts> list = pageInfo.getList();
        Map<String, Object> response = new HashMap<>();
        List<String> usernames = new ArrayList<>();
        if (list.isEmpty()) {
            response.put("info", "暂无帖子");
        }
        for (Posts posts1 : list) {
            User user = userService.getUserById(posts1.getUserId());
            usernames.add(user.getUsername());
        }
        response.put("list", list);
        response.put("usernameList", usernames);
        response.put("totalPage", pageInfo.getPages());

        User admin = (User) request.getSession().getAttribute("user");
        response.put("admin",admin);
        return response;
    }

    @ApiOperation("通过帖子审核")
    @GetMapping("/toApprovePost")
    public String approvePost(@RequestParam("id") int id, RedirectAttributes redirectAttributes)
            throws BusinessException {
        // 重定向方法，无需 ModelAndView，故不处理
        adminService.approvePost(id);
        redirectAttributes.addFlashAttribute("info", "审核通过");
        return "redirect:/admin/behindManagerPost";
    }

    @ApiOperation("拒绝帖子审核")
    @GetMapping("/toRejectPost")
    public String rejectPost(@RequestParam("id") int id, RedirectAttributes redirectAttributes)
            throws BusinessException {
        // 重定向方法，无需 ModelAndView，故不处理
        redirectAttributes.addFlashAttribute("info", "审核不通过");
        return "redirect:/admin/behindManagerPost";
    }

    // 用户管理
    @ApiOperation("查询所有用户")
    @GetMapping("/behindManagerUser")
    public ModelAndView searchUser(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                   @RequestParam(value = "pageSize", defaultValue = "4") int pageSize,
                                   HttpServletRequest request) throws BusinessException { // 添加 request 参数
        PageInfo<User> pageInfo = adminService.getUsersFromManagerWithPaging(pageNum, pageSize);
        ModelAndView mav = new ModelAndView("behindManagerUser");
        List<User> list = pageInfo.getList();
        for(User user:list){
            user.setEmail("***");
            user.setPassword("***");
        }
        mav.addObject("userList", list);
        mav.addObject("totalPages", pageInfo.getPages());


        User admin = (User) request.getSession().getAttribute("user");
        mav.addObject("admin", admin);

        return mav;
    }

    @ApiOperation("用户分页")
    @ResponseBody
    @GetMapping("/getUsersFromManagerWithPaging")
    public Map<String, Object> getUsersFromManagerWithPaging(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                                             @RequestParam(value = "pageSize", defaultValue = "4") int pageSize,
                                                             HttpServletRequest request) {

        PageInfo<User> pageInfo = adminService.getUsersFromManagerWithPaging(pageNum, pageSize);
        List<User> list = pageInfo.getList();
        for(User user:list){
            user.setEmail("***");
            user.setPassword("***");
        }
        Map<String, Object> response = new HashMap<>();
        if (list.isEmpty()) {
            response.put("info", "暂无用户");
        }
        response.put("list", list);
        response.put("totalPage", pageInfo.getPages());

        User admin = (User) request.getSession().getAttribute("user");
        response.put("admin",admin);
        return response;
    }

    @ApiOperation("添加用户")
    @PostMapping("/toAddUser")
    public String addUser(
            @RequestParam("username") String username,
            @RequestParam("email") String email,
            @RequestParam("password") String password,
            @RequestParam("gender") String gender,
            @RequestParam("avatar") String avatar,
            @RequestParam("bio") String bio,
            @RequestParam("shortBio") String shortBio,
            @RequestParam("location") String location,
            @RequestParam("industry") String industry,
            RedirectAttributes redirectAttributes) throws BusinessException {

        if (userService.checkUsernameExists(username)) {
            redirectAttributes.addFlashAttribute("error", "用户名已存在");
            return "redirect:/admin/behindManagerUser";
        }
        User user = new User();
        user.setUsername(username);
        user.setEmail(email);
        user.setPassword(password);
        user.setGender(gender);
        user.setAvatar(avatar);
        user.setBio(bio);
        user.setShortBio(shortBio);
        user.setIndustry(industry);
        user.setLocation(location);
        userService.insertUser(user);
        redirectAttributes.addFlashAttribute("info", "添加成功");
        return "redirect:/admin/behindManagerUser";
    }

    @ApiOperation("删除用户")
    @GetMapping("/toDeleteUser")
    public String deleteUser(@RequestParam("id") int id, RedirectAttributes redirectAttributes)
            throws BusinessException {

        userService.deleteUserById(id);
        redirectAttributes.addFlashAttribute("info", "删除成功");
        return "redirect:/admin/behindManagerUser";
    }

    @ApiOperation("获取用户编辑信息")
    @GetMapping("/toUpdateUserPage")
    public ResponseEntity<?> toUpdateUserPage(@RequestParam("id") int id) {
        try {
            User user = userService.getUserById(id);
                user.setEmail("***");
                user.setPassword("***");

            if (user == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "用户不存在");
            }
            Map<String, Object> response = new LinkedHashMap<>();
            response.put("code", HttpStatus.OK.value());
            response.put("message", "success");
            response.put("user", user);
            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            Map<String, Object> error = new LinkedHashMap<>();
            error.put("code", e.getErrorCode());
            error.put("message", e.getErrorMessage());
            return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
        } catch (Exception e) {
            Map<String, Object> error = new LinkedHashMap<>();
            error.put("code", Code.SYSTEM_DB_ERROR);
            error.put("message", "获取用户信息失败");
            return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @ApiOperation("更新用户信息")
    @PostMapping("/toUpdateUser")
    public String updateUser(
            @RequestParam("id") int id,
            @RequestParam("username") String username,
            @RequestParam("email") String email,
            @RequestParam("password") String password,
            @RequestParam("gender") String gender,
            @RequestParam("avatar") String avatar,
            @RequestParam("bio") String bio,
            @RequestParam("shortBio") String shortBio,
            @RequestParam("location") String location,
            @RequestParam("industry") String industry,
            RedirectAttributes redirectAttributes) throws BusinessException {

        User user = userService.getUserById(id);
        if (user == null) {
            redirectAttributes.addFlashAttribute("error", "用户不存在");
            return "redirect:/admin/behindManagerUser";
        }
        if (!user.getUsername().equals(username) && userService.checkUsernameExists(username)) {
            redirectAttributes.addFlashAttribute("error", "用户名已存在");
            redirectAttributes.addAttribute("id", id); // 保留ID参数
            return "redirect:/admin/behindManagerUser";
        }
        user.setUsername(username);
        user.setEmail(email);
        user.setPassword(password);
        user.setGender(gender);
        user.setAvatar(avatar);
        user.setBio(bio);
        user.setShortBio(shortBio);
        user.setIndustry(industry);
        user.setLocation(location);
        userService.updateUser(user);
        redirectAttributes.addFlashAttribute("info", "修改成功");
        return "redirect:/admin/behindManagerUser";
    }

    @ApiOperation("禁言用户")
    @GetMapping("/muteUser")
    public String muteUser(@RequestParam("id") int id, RedirectAttributes redirectAttributes)
            throws BusinessException {
        adminService.muteUser(id);
        redirectAttributes.addFlashAttribute("info", "禁言成功");
        return "redirect:/admin/behindManagerUser";
    }

    @ApiOperation("解除禁言")
    @GetMapping("/unMuteUser")
    public String unMuteUser(@RequestParam("id") int id, RedirectAttributes redirectAttributes)
            throws BusinessException {
        adminService.unMuteUser(id);
        redirectAttributes.addFlashAttribute("info", "解除禁言");
        return "redirect:/admin/behindManagerUser";
    }

    // 举报管理
    @ApiOperation("查询举报信息")
    @GetMapping("/behindManagerReport")
    public ModelAndView selectAllReportedInfo(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                              @RequestParam(value = "pageSize", defaultValue = "4") int pageSize,
                                              HttpServletRequest request) throws BusinessException { // 添加 request 参数
        PageInfo<ReportInfo> pageInfo = adminService.getReportInfoFromManagerWithPaging(pageNum, pageSize);
        List<String> reporterList = new ArrayList<>();
        List<String> postUserList = new ArrayList<>();
        List<Posts> postsList = new ArrayList<>();

        for (ReportInfo reportInfo : pageInfo.getList()) {
            User reporter = userService.getUserById(reportInfo.getReporterId());
            reporterList.add(reporter.getUsername());

            Posts post = postsServiceImpl.selectById(reportInfo.getPostId());
            postsList.add(post);
            User postUser = userService.getUserById(post.getUserId());
            postUser.setEmail("***");
            postUser.setPassword("***");
            postUserList.add(postUser.getUsername());
        }

        ModelAndView mav = new ModelAndView("behindManagerReport");
        mav.addObject("postList", postsList);
        mav.addObject("postUserList", postUserList);
        mav.addObject("reporterList", reporterList);
        mav.addObject("reportInfoList", pageInfo.getList());
        mav.addObject("totalPage", pageInfo.getPages());

        // 添加 admin 对象
        User admin = (User) request.getSession().getAttribute("user");
        mav.addObject("admin", admin);

        return mav;
    }

    @ApiOperation("举报信息分页")
    @ResponseBody
    @GetMapping("/getReportInfoFromManagerWithPaging")
    public Map<String, Object> getReportInfoFromManagerWithPaging(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                                                  @RequestParam(value = "pageSize", defaultValue = "4") int pageSize,
                                                                  HttpServletRequest request) {

        PageInfo<ReportInfo> pageInfo = adminService.getReportInfoFromManagerWithPaging(pageNum, pageSize);
        List<ReportInfo> list = pageInfo.getList();
        List<String> reporterList = new ArrayList<>();
        List<String> postUserList = new ArrayList<>();
        List<Posts> postsList = new ArrayList<>();

        for (ReportInfo reportInfo : list) {
            User reporter = userService.getUserById(reportInfo.getReporterId());
            reporterList.add(reporter.getUsername());

            Posts post = postsServiceImpl.selectById(reportInfo.getPostId());
            postsList.add(post);
            User postUser = userService.getUserById(post.getUserId());
            postUserList.add(postUser.getUsername());
        }

        Map<String, Object> response = new HashMap<>();
        if (list.isEmpty()) {
            response.put("info", "暂无举报信息");
        }
        response.put("postList", postsList);
        response.put("postUserList", postUserList);
        response.put("reporterList", reporterList);
        response.put("reportInfoList", list);
        response.put("list", list);
        response.put("totalPage", pageInfo.getPages());

        User admin = (User) request.getSession().getAttribute("user");
        response.put("admin",admin);
        return response;
    }

    @ApiOperation("处理举报成功")
    @GetMapping("/toApproveTheReportedInfo")
    public String approveTheReportedInfo(
            @RequestParam("id") int id,
            RedirectAttributes redirectAttributes) throws BusinessException {
        reportInfoService.reportSuccessfully(id);
        redirectAttributes.addFlashAttribute("info", "处理成功");
        return "redirect:/admin/behindManagerReport"; // 修正URL，添加 /admin 前缀
    }

    @ApiOperation("处理举报失败")
    @GetMapping("/toRejectTheReportInfo")
    public String rejectTheReportedInfo(
            @RequestParam("id") int id,
            RedirectAttributes redirectAttributes) throws BusinessException {
        reportInfoService.reportFail(id);
        redirectAttributes.addFlashAttribute("info", "处理失败");
        return "redirect:/admin/behindManagerReport"; // 修正URL，添加 /admin 前缀
    }

//    // 评论审核
//    @ApiOperation("审核中的评论")
//    @GetMapping("/behindManagerComment")
//    public ModelAndView selectAllCommentUnderChecking(HttpServletRequest request) { // 添加 request 参数
//        List<Comments> comments = adminService.commentsUnderChecking();
//        List<String> userList = new ArrayList<>();
//        List<String> postList = new ArrayList<>();
//
//        for (Comments comment : comments) {
//            User user = userService.getUserById(comment.getUserId());
//            userList.add(user.getUsername());
//            Posts post = postsServiceImpl.selectById(comment.getPostId());
//            postList.add(post.getTitle());
//        }
//
//        ModelAndView mav = new ModelAndView("behindManagerComment");
//        mav.addObject("commentList", comments);
//        mav.addObject("userList", userList);
//        mav.addObject("postList", postList);
//
//        // 添加 admin 对象
//        User admin = (User) request.getSession().getAttribute("user");
//        mav.addObject("admin", admin);
//
//        return mav;
//    }
//
//    @ApiOperation("拒绝评论")
//    @GetMapping("/toRejectTheCommentInfo")
//    public String rejectComment(
//            @RequestParam("id") int id,
//            RedirectAttributes redirectAttributes) throws BusinessException {
//        adminService.rejectComment(id);
//        redirectAttributes.addFlashAttribute("info", "审核拒绝");
//        return "redirect:/admin/behindManagerComment";
//    }
//
//    @ApiOperation("通过评论")
//    @GetMapping("/toApproveTheCommentInfo")
//    public String approveComment(
//            @RequestParam("id") int id,
//            RedirectAttributes redirectAttributes) throws BusinessException {
//        // 重定向方法，无需 ModelAndView，故不处理
//        adminService.approveComment(id);
//        redirectAttributes.addFlashAttribute("info", "审核通过");
//        return "redirect:/admin/behindManagerComment";
//    }

    @ApiOperation("模糊查询用户")
    @GetMapping("/fuzzyQueryUser")
    public ModelAndView fuzzyQueryUser(@RequestParam("keyWord") String keyWord, HttpServletRequest request) { // 添加 request 参数
        ModelAndView mav = new ModelAndView();
        User user = adminService.fuzzyQueryUser(keyWord);
        mav.addObject("user", user);
        mav.setViewName("/behindManagerUser");

        // 添加 admin 对象
        User admin = (User) request.getSession().getAttribute("user");
        mav.addObject("admin", admin);

        return mav;
    }

}